#!/bin/bash
# 应用数据库修复脚本

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "[INFO] Applying database fixes..."
echo "[INFO] Project root: $PROJECT_ROOT"

# 数据库连接信息
DB_HOST="localhost"
DB_PORT="31432"
DB_NAME="insight"
DB_USER="dgp_user"
DB_PASSWORD="dgp_password"

# SQL修复脚本路径
SQL_FILE="$PROJECT_ROOT/src/main/resources/db/fix-collection-task-complete.sql"

if [ ! -f "$SQL_FILE" ]; then
    echo "[ERROR] SQL file not found: $SQL_FILE"
    exit 1
fi

echo "[INFO] Using SQL file: $SQL_FILE"
echo "[INFO] Connecting to database: $DB_HOST:$DB_PORT/$DB_NAME"

# 尝试使用docker exec执行SQL
CONTAINER_ID=$(docker ps | grep postgres | awk '{print $1}' | head -1)

if [ -n "$CONTAINER_ID" ]; then
    echo "[INFO] Found PostgreSQL container: $CONTAINER_ID"

    # 将SQL文件复制到容器中
    docker cp "$SQL_FILE" "$CONTAINER_ID:/tmp/fix.sql"

    # 执行SQL
    export PGPASSWORD="$DB_PASSWORD"
    docker exec -i "$CONTAINER_ID" psql -U "$DB_USER" -d "$DB_NAME" -f /tmp/fix.sql

    if [ $? -eq 0 ]; then
        echo "[SUCCESS] Database fixes applied successfully"

        # 验证列是否存在
        docker exec -i "$CONTAINER_ID" psql -U "$DB_USER" -d "$DB_NAME" -c "SELECT column_name, data_type FROM information_schema.columns WHERE table_name='collection_task' AND column_name IN ('collection_type', 'tables_collected', 'tables_total') ORDER BY column_name;"
    else
        echo "[ERROR] Failed to apply database fixes"
        exit 1
    fi
else
    echo "[WARNING] No PostgreSQL container found. Please apply the SQL manually."
    echo "[INFO] SQL file location: $SQL_FILE"
    echo "[INFO] Connection: psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -f $SQL_FILE"
fi
